package com.ihighest.app.infox.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.HistoryListviewAdapter;
import com.ihighest.app.infox.adapter.ImageListviewAdapter;
import com.ihighest.app.infox.myview.AKListView;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.HorizontialListView;

/**
 * 回答详情
 * 
 * @author lkx Created at 2015-11-19 下午5:27:36
 * @version 1.0
 */
public class AnswerDetailActivity extends BaseActivity {
	private ActivityTitle title;

	private String qid = "";// 问题id
	private String name = "", image, content, state, area, tag, rid, voice, uid;
	 private String plantname, gold, weather, measure;
	// private TextView plantnameTextView, goldTextView, weatherTextView,
	// measureTextView;

	private final String fileFolder = Environment.getExternalStorageDirectory().getPath() + "/infox/";
	File viocefile;
	String path = "";

	private TextView nametTextView, addresTextView, timeTextView, tagTextView, contentTextView, stateTextView, answerTextView;

	private HorizontialListView imagesListView;
	private ArrayList<String> imagelist;

	private int answers;
	private long time;
	private Boolean fav = false;

	private ImageView iconimage;
	private ImageView voiceimage;
	private ImageListviewAdapter imageListviewAdapter;
	JSONArray images;
	AKListView answerList;
	String tmid;
	int page = 1;
	long longtime = 0;// 加载时间戳
	private JSONArray jsonarray;

	private HistoryListviewAdapter adapter;

	private TextView emptyview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.infox_activity_answerdetail);
		title = (ActivityTitle) findViewById(R.id.questionContentTitle);
		title.setViewVersible(title.titleBack);
		title.setViewGone(title.titleMsg, title.titleSetting, title.titleRefresh, title.rightLayout);
		imagelist = new ArrayList<String>();
		qid = getIntent().getStringExtra("qid");
		tmid = getIntent().getStringExtra("tmid");
		getquestiondata();
		/*
		 * gethistory(); jsonarray = new JSONArray(); answerList = (AKListView)
		 * findViewById(R.id.answerList); adapter = new
		 * HistoryListviewAdapter(jsonarray, this);
		 * answerList.setAdapter(adapter);
		 */

		iconimage = (ImageView) findViewById(R.id.questionContentUserImg);
	//	nametTextView = (TextView) findViewById(R.id.questionContentUserName);
	//	addresTextView = (TextView) findViewById(R.id.questionContentUserAddress);
	//	timeTextView = (TextView) findViewById(R.id.questionContentDate);
	//	tagTextView = (TextView) findViewById(R.id.questionContentAttribute);
		contentTextView = (TextView) findViewById(R.id.questionContentQuestion);
	//	stateTextView = (TextView) findViewById(R.id.questionSolve);
	//	answerTextView = (TextView) findViewById(R.id.questionAnswerCount);
		imagesListView = (HorizontialListView) findViewById(R.id.questionContentImglist);

		voiceimage = (ImageView) findViewById(R.id.id_voice);
	//	plantnameTextView = (TextView) findViewById(R.id.id_plantname);
	//	weatherTextView = (TextView) findViewById(R.id.id_weather);
	//	measureTextView = (TextView) findViewById(R.id.id_measure);
	//	goldTextView = (TextView) findViewById(R.id.id_gold);

	}

	/**
	 * 
	 * 请求聊天记录
	 * 
	 * 
	 * 
	 * @author yyh Created at 2015-11-20 上午10:47:54
	 */
	private void gethistory() {
		// TODO Auto-generated method stub
		ApiParam param = ApiParam.create();
		param.addParam("page", page);
		param.addParam("bid", qid);
		param.addParam("channelType", "PERSON");
		param.addParam("tmid", tmid);
		if (longtime != 0) {
			param.addParam("time", longtime);

		}
		Api.get("chat/history", param, new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				// TODO Auto-generated method stub
				if (result.getCode() == 100) {
					longtime = result.getTime();

					if (page == 1) {

						jsonarray = result.getDatas();
						adapter.setData(jsonarray);

					} else {

						try {
							jsonarray = AppKit.joinJSONArray(jsonarray, result.getDatas());
							adapter.appendData(jsonarray);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				}
				// answerList.onRefreshComplete();
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub
				// answerList.onRefreshComplete();
			}
		}, this);

	}

	/**
	 * 获取问题详情
	 * 
	 * 
	 * 
	 * @author yyh Created at 2015-11-2 下午4:03:41
	 */
	private void getquestiondata() {

		Api.post("qa/issueDetail", ApiParam.create().addParam("id", qid), new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				try {
					image = result.getData().getString("image");
					name = result.getData().getString("mname");
					area = result.getData().getString("area");
					time = result.getData().getLong("time");
					content = result.getData().getString("content");
					state = result.getData().getString("state");
					rid = result.getData().getString("rid");
					tag = result.getData().getString("tag");
					answers = result.getData().getInt("answers");
					fav = result.getData().getBoolean("fav");
					voice = result.getData().getString("voice");
					images = result.getData().getJSONArray("images");
					uid = result.getData().getString("uid");

				//	plantname = result.getData().getString("name");
				//	gold = result.getData().getString("gold");
				//	weather = result.getData().getString("weather");
				//	measure = result.getData().getString("measure");

					for (int i = 0; i < images.length(); i++) {
						imagelist.add((String) images.get(i));
					}

					init();
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(), e);
				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				ToastKit.show(AnswerDetailActivity.this, "加载失败", Toast.LENGTH_SHORT);
			}
		}, this);

	}

	private void init() {

		jsonarray = new JSONArray();
		answerList = (AKListView) findViewById(R.id.answerList);
		adapter = new HistoryListviewAdapter(jsonarray, this, rid);
		answerList.setAdapter(adapter);

//		nametTextView.setText(name);
//		if (name.length() > 5) {
//			name = name.substring(0, 4) + "...";
//		}

		title.setTitle("回答详情");

		// 分享

		title.setOtherImg(R.drawable.infox_title_share);

		title.titleOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});
		// 收藏
		if (fav) {

			title.setSecondImg(R.drawable.infox_content_collection_perss);
		} else {
			title.setSecondImg(R.drawable.infox_person_get);

		}

		title.titleSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(AnswerDetailActivity.this, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(AnswerDetailActivity.this, LoginActivity.class);
					ToastKit.showShort(AnswerDetailActivity.this, Const.UN_LOGIN_ALERT);
					startActivity(intent);
				} else {

					Api.post("me/favorite", ApiParam.create().addParam("id", qid).addParam("type", 4).addParam("action", fav ? 2 : 1),
							new ApiCallback(AnswerDetailActivity.this, true) {

								@Override
								public void handleSuccess(ApiResult result) {
									if (fav) {
										title.setSecondImg(R.drawable.infox_person_get);
										fav = false;
									} else {
										title.setSecondImg(R.drawable.infox_content_collection_perss);
										fav = true;
									}
								}

								@Override
								public void handleFailure(Exception e, String msg) {
									ToastKit.showShort(mContext, "收藏失败");
								}
							}, AnswerDetailActivity.this);

				}
			}
		});
		if (imagelist.size() == 0) {
			imagesListView.setVisibility(View.GONE);
		} else {
			imageListviewAdapter = new ImageListviewAdapter(this, imagelist);
			imagesListView.setVisibility(View.VISIBLE);
			imagesListView.setAdapter(imageListviewAdapter);
		}
		// DisplayImageOptions defaultOptions = new
		// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_person_no_icon)
		// .showImageOnFail(R.drawable.infox_person_no_icon).showImageOnLoading(R.drawable.infox_person_no_icon).cacheInMemory(true)
		// .cacheOnDisc(true).build();
		// ImageLoader.getInstance().displayImage(image, iconimage,
		// defaultOptions);
		AppKit.SetUserImg(image, iconimage);

		if (area.length() > 5) {
			area = area.substring(0, 5);
		}

//		addresTextView.setText(area);
		contentTextView.setText(content);
//		tagTextView.setText(tag);
//
//		timeTextView.setText(AppKit.timeToBeforeStr(time));
//
//		plantnameTextView.setText(plantnameTextView.getText() + plantname);
//
//		if (weather == null || "".equals(weather)) {
//			weatherTextView.setText(weatherTextView.getText() + "未填写");
//		} else {
//			weatherTextView.setText(weatherTextView.getText() + weather);
//		}
//
//		if (measure == null || "".equals(measure)) {
//			measureTextView.setText(measureTextView.getText() + "未填写");
//		} else {
//			measureTextView.setText(measureTextView.getText() + measure);
//
//		}
//		if (gold == null || "".equals(gold)) {
//			goldTextView.setText(goldTextView.getText());
//		} else {
//
//			goldTextView.setText(goldTextView.getText() + gold);
//
//		}
//
//		if (state == null || state.equals("0")) {
//			stateTextView.setText("未解决");
//			stateTextView.setBackgroundResource(R.drawable.infox_information_hotbg);
//			stateTextView.setTextColor(this.getResources().getColor(R.color.not_resolve_color));
//
//		} else {
//			stateTextView.setText("已解决");
//			stateTextView.setBackgroundResource(R.drawable.infox_information_dingyuebg);
//			stateTextView.setTextColor(this.getResources().getColor(R.color.resolve_color));
//
//		}
//		answerTextView.setText(answers + "人回答");
//
//		emptyview = new TextView(this);
//		emptyview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//		emptyview.setText("暂无追问");
//		emptyview.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
//		emptyview.setVisibility(View.GONE);
//		answerList.setEmptyView(emptyview);

		System.out.println(voice);

		if (voice == null || voice.equals("")) {
			voiceimage.setVisibility(View.GONE);
		} else {
			voiceimage.setVisibility(View.VISIBLE);
			downloadVoice();

			voiceimage.setOnClickListener(new OnClickListener() {

				private MediaPlayer player;

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub

					if (path == null || path.equals("")) {
						return;

					}

					if (player == null) {

						player = new MediaPlayer();
						// player.setAudioStreamType(AudioManager.STREAM_ALARM);

					}
					try {
						player.reset();
						System.out.println(voice);
						player.setDataSource(viocefile.getPath());
						System.out.println(viocefile.getPath());
						System.out.println(path);
						player.prepare();
						player.start();

						// System.out.println(player.getDuration());

						player.setOnCompletionListener(new OnCompletionListener() {

							@Override
							public void onCompletion(MediaPlayer arg0) {
								// TODO Auto-generated method stub
								Log.e("oncompletion", "voicestop");
								player.stop();
								player.release();
								player = null;
								voiceimage.setClickable(true);
							}
						});

					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			});
		}

		gethistory();
	}

	/**
	 * 
	 * 加载声音文件
	 * 
	 * 
	 * @author yyh Created at 2015-11-10 上午10:58:23
	 */
	private void downloadVoice() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				String newFilename = voice.substring(voice.lastIndexOf("/") + 1);

				File file = new File(fileFolder);
				if (!file.exists()) {
					file.mkdir();
				}
				path = newFilename = fileFolder + newFilename;
				viocefile = new File(path);
				// 如果目标文件已经存在，则删除。产生覆盖旧文件的效果
				if (viocefile.exists()) {
					viocefile.delete();
				}
				try {
					// 构造URL
					URL url = new URL(voice);
					// 打开连接
					URLConnection con = url.openConnection();

					con.connect();
					// 获得文件的长度
					int contentLength = con.getContentLength();
					System.out.println("长度 :" + contentLength);
					// 输入流
					InputStream is = con.getInputStream();
					// 1K的数据缓冲
					byte[] bs = new byte[1024];
					// 读取到的数据长度
					int len;
					// 输出的文件流
					OutputStream os = new FileOutputStream(viocefile);
					// 开始读取
					while ((len = is.read(bs)) != -1) {
						os.write(bs, 0, len);
					}
					// 完毕，关闭所有链接
					os.close();
					is.close();

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();

	}

}
